package com.qdxwx.captcha.impl;

import com.qdxwx.captcha.GimpyEngine;
import com.qdxwx.captcha.NoiseProducer;
import com.qdxwx.captcha.filters.image.RippleFilter;
import com.qdxwx.captcha.filters.image.TransformFilter;
import com.qdxwx.captcha.filters.image.WaterFilter;
import com.qdxwx.captcha.util.Configurable;

import java.awt.*;
import java.awt.image.BufferedImage;

public class WaterRipple extends Configurable implements GimpyEngine
{
    /**
     * Applies distortion by adding water ripple effect.
     *
     * @param baseImage the base image
     * @return the distorted image
     */
    public BufferedImage getDistortedImage(BufferedImage baseImage)
    {
        NoiseProducer noiseProducer = getConfig().getNoiseImpl();
        BufferedImage distortedImage = new BufferedImage(baseImage.getWidth(),
                baseImage.getHeight(), BufferedImage.TYPE_INT_ARGB);

        Graphics2D graphics = (Graphics2D) distortedImage.getGraphics();

        RippleFilter rippleFilter = new RippleFilter();
        rippleFilter.setWaveType(RippleFilter.SINE);
        rippleFilter.setXAmplitude(2.6f);
        rippleFilter.setYAmplitude(1.7f);
        rippleFilter.setXWavelength(15);
        rippleFilter.setYWavelength(5);
        rippleFilter.setEdgeAction(TransformFilter.NEAREST_NEIGHBOUR);

        WaterFilter waterFilter = new WaterFilter();
        waterFilter.setAmplitude(1.5f);
        waterFilter.setPhase(10);
        waterFilter.setWavelength(2);

        BufferedImage effectImage = waterFilter.filter(baseImage, null);
        effectImage = rippleFilter.filter(effectImage, null);

        graphics.drawImage(effectImage, 0, 0, null, null);

        graphics.dispose();

        noiseProducer.makeNoise(distortedImage, .1f, .1f, .25f, .25f);
        noiseProducer.makeNoise(distortedImage, .1f, .25f, .5f, .9f);
        return distortedImage;
    }
}
